
package com.devo.icecream.ui.advertising

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import com.devo.icecream.AppLogger
import com.devo.icecream.data.APIClient
import com.devo.icecream.data.Advertising
import com.devo.icecream.ui.BaseActivity
import com.devo.icecream.ui.theme.IcecreamTheme
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch

class AdvertActivity : BaseActivity() {

    private val advertisingList = MutableStateFlow<List<Advertising>>(arrayListOf())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            try {
                advertisingList.tryEmit(APIClient.getAdverts())
            } catch (e: Exception) {
                AppLogger.e(e, "拉取广告报错")
            }
        }
        setContent {
            IcecreamTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    val adverts = advertisingList.collectAsState()

                    AdvertScreen(adverts.value) {
                        finish()
                    }
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        lifecycleScope.launch {
            try {
                advertisingList.tryEmit(APIClient.getAdverts())
            } catch (e: Exception) {
                AppLogger.e(e, "拉取广告报错")
            }
        }
    }


}